package edu.tjut.tjutcommunity.controller;


import edu.tjut.tjutcommunity.entity.*;
import edu.tjut.tjutcommunity.service.FloorService;
import edu.tjut.tjutcommunity.service.PostlogsService;
import edu.tjut.tjutcommunity.service.UserService;
import edu.tjut.tjutcommunity.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yhh
 * @since 2022-04-17
 */
@RestController
@RequestMapping("/floor")
public class FloorController {
    final
    FloorService floorService;
    final
    UserService userService;

    final
    PostlogsService postlogsService;

    public FloorController(FloorService floorService, UserService userService, PostlogsService postlogsService) {
        this.floorService = floorService;
        this.userService = userService;
        this.postlogsService = postlogsService;
    }

    @PostMapping("/floor")
    public Message floor(@RequestParam("pid") Integer pid, @RequestParam("pageNo") Integer pageNo) {
        PageResult<Floor> result = floorService.getFloor(pid, pageNo);
        return Message.ok(result);
    }

    @GetMapping("/getmyfloors")
    public Message getmyfloors(){
        String stuId = UserUtil.getCurStuId();
        User user = userService.getUserByStuId(stuId);
        List<Integer> result = floorService.getMyFloors(user.getUid());
        return Message.ok(result);
    }

    @PostMapping("/publishFloor")
    public Message publish(@RequestBody Floor floor) {
        String stuId = UserUtil.getCurStuId();
        User user = userService.getUserByStuId(stuId);
        if (user == null) return Message.failed("用户不存在");
        if (floorService.addFloor(floor, user) != null) {
            postlogsService.insert(user, floor.getPid(), 1);
            return Message.ok(floor);
        }
        return Message.failed();
    }


    @GetMapping("/like/{fid}")
    public Message like(@PathVariable Integer fid) {
        String stuId = UserUtil.getCurStuId();
        User user = userService.getUserByStuId(stuId);
        user.setStudentId(stuId);
        //在此处通知被赞者
        if (floorService.likeInc(fid, user)) {
            return Message.ok();
        }
        return Message.failed();
    }

    @GetMapping("/del/{fid}")
    public Message delPost(@PathVariable Integer fid) {
        String stuId = UserUtil.getCurStuId();
        User user = userService.getUserByStuId(stuId);
        if (!floorService.delFloor(fid, user)) {
            return Message.failed("删除失败");
        }
        return Message.ok("删除成功");
    }


}

